<template>
  <div class="info-drawer">
    <el-drawer :model-value="isShowDrawer" :title="modelName" @close="close">
      <el-form :model="form" :rules="rules" ref="formRef">
        <h2 style="margin-bottom: 20px">名称</h2>
        <div class="label">
          <div v-if="labelEditing" style="flex-grow: 1">
            <el-form-item prop="modelName">
              <el-input
                v-model="form.modelName"
                maxlength="20"
                show-word-limit
                style="margin: 5px"
                placeholder="请输入模块名称"
              ></el-input>
            </el-form-item>
          </div>
          <div v-else style="flex-grow: 1; margin-left: 15px; font-size: 14px">
            {{ form.modelName }}
          </div>
          <el-button
            :disabled="describeEditing || activityEditing !== null"
            :type="labelEditing ? 'success' : 'primary'"
            :icon="labelEditing ? Check : Edit"
            circle
            @click="labelEditing ? labelFinishEditing() : labelStartEditing()"
            style="margin: 5px 0 20px 20px"
          />
        </div>
        <h2 style="margin-bottom: 20px">描述</h2>
        <div class="describe">
          <div v-if="describeEditing" style="flex-grow: 1">
            <el-form-item prop="modelDescribe">
              <el-input
                v-model="form.modelDescribe"
                maxlength="600"
                size="large"
                show-word-limit
                style="margin: 5px"
                :autosize="{ maxRows: 10 }"
                type="textarea"
                resize="none"
                placeholder="请输入模块描述"
              ></el-input>
            </el-form-item>
          </div>
          <div
            v-else
            style="
              flex-grow: 1;
              margin-left: 15px;
              font-size: 14px;
              white-space: normal;
              word-wrap: break-word;
            "
          >
            {{ form.modelDescribe }}
          </div>
          <el-button
            :disabled="labelEditing || activityEditing !== null"
            :type="describeEditing ? 'success' : 'primary'"
            :icon="describeEditing ? Check : Edit"
            circle
            @click="describeEditing ? describeFinishEditing() : describeStartEditing()"
            style="margin: 5px 0 20px 20px"
          />
        </div>
        <div class="activity">
          <h2 style="margin-bottom: 20px">活动</h2>
          <el-table :data="filterTableData" style="width: 100%" max-height="500">
            <el-table-column label="活动状态" prop="activityStatus">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.activityStatus)">
                  {{ getActivityStatusText(scope.row.activityStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="活动名称" prop="activityName">
              <template #default="scope">
                <div v-if="activityEditing === scope.row.activityId">
                  <el-input
                    v-model="scope.row.activityName"
                    maxlength="10"
                    placeholder="编辑活动名称"
                  ></el-input>
                </div>
                <div v-else>
                  {{ scope.row.activityName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="活动描述" prop="activityDescribe">
              <template #default="scope">
                <div v-if="activityEditing === scope.row.activityId">
                  <el-input
                    v-model="scope.row.activityDescribe"
                    maxlength="20"
                    show-word-limitplaceholder="编辑活动描述"
                  ></el-input>
                </div>
                <div v-else>
                  {{ scope.row.activityDescribe }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="right">
              <template #header>
                <el-input v-model="search" size="small" placeholder="搜索活动名称" />
              </template>
              <template #default="scope">
                <el-button
                  :disabled="
                    labelEditing ||
                    describeEditing ||
                    (activityEditing !== null && activityEditing !== scope.row.activityId)
                  "
                  size="small"
                  :type="activityEditing === scope.row.activityId ? 'success' : 'primary'"
                  plain
                  @click="handleEdit(scope.$index, scope.row)"
                >
                  {{ activityEditing === scope.row.activityId ? '完成' : '编辑' }}
                </el-button>
                <el-button
                  :disabled="labelEditing || describeEditing || activityEditing !== null"
                  size="small"
                  type="danger"
                  plain
                  @click="handleDelete(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            :disabled="labelEditing || describeEditing || activityEditing !== null"
            type="success"
            plain
            style="width: 100%"
            @click="onAddItem"
          >
            添加活动
          </el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import type { Ref } from 'vue'
import { defineEmits, ref, watch, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Edit } from '@element-plus/icons-vue'
import { moveModelRequest } from '@/service/model/model'
import {
  addActivity,
  delActivity,
  getActivityByModel,
  updateActivity
} from '@/service/activity/activity'

const props = defineProps({
  isShowDrawer: {
    type: Boolean,
    required: true
  },
  modelId: {
    type: String,
    required: true
  },
  modelName: {
    type: String,
    required: true
  },
  modelDescribe: {
    type: String,
    required: true
  }
})
const emit = defineEmits(['update:isShowDrawer', 'update:model'])
const labelEditing = ref(false)
const describeEditing = ref(false)
const activityEditing: Ref<string | null> = ref(null)
const formRef = ref()

interface activity {
  activityId: string
  activityStatus: string
  activityName: string
  activityDescribe: string
}
const getTagType = (status: number) => {
  console.log('Status:', status) // 输出查看状态值
  switch (status) {
    case 1:
      return 'primary'
    case 2:
      return 'success'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

const getActivityStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '待发布'
    case 2:
      return '实施中'
    case 3:
      return '已完成'
    default:
      return '未知状态'
  }
}
const search = ref('')
//编辑活动
const handleEdit = async (index: number, row: activity) => {
  if (activityEditing.value === row.activityId) {
    await updateActivity(row)
    await getActivityList(props.modelId)
    activityEditing.value = null
    ElMessage.success('活动修改完成')
  } else {
    // 否则，设置当前活动为编辑状态
    activityEditing.value = row.activityId
  }
}
//删除活动
const handleDelete = async (index: number) => {
  await delActivity(tableData.value[index].activityId)
  await getActivityList(props.modelId)
  ElMessage.success('删除成功')
}
//添加活动
const onAddItem = async () => {
  await addActivity({
    modelId: props.modelId,
    activityName: '新建活动',
    activityDescribe: '新建活动描述',
    activityStatus: 1
  })
  await getActivityList(props.modelId)
  ElMessage.success('添加成功')
}
//查询活动
const getActivityList = async (modelId: string) => {
  const res = await getActivityByModel(modelId)
  tableData.value = res.data
  console.log('tableData:', tableData.value)
}
const tableData = ref([] as activity[])

watch(
  () => props.modelId,
  async (newModelId) => {
    await getActivityList(newModelId)
  }
)
const filterTableData = computed(() => {
  return tableData.value.filter((data) =>
    data.activityName.toLowerCase().includes(search.value.toLowerCase())
  )
})
watch(
  () => props.modelName,
  (newLabel) => {
    form.modelName = newLabel
  }
)
watch(
  () => props.modelDescribe,
  (newDescribe) => {
    form.modelDescribe = newDescribe
  }
)
const labelStartEditing = () => {
  labelEditing.value = !labelEditing.value
}
const labelFinishEditing = async () => {
  try {
    await formRef.value.validate()
    await moveModelRequest({
      modelId: props.modelId,
      modelName: form.modelName
    })
    labelEditing.value = false
    emit('update:model', form.modelName, form.modelDescribe)
    ElMessage.success('名称修改完成')
  } catch (err) {
    console.error('验证失败', err)
  }
}
const describeStartEditing = () => {
  describeEditing.value = !describeEditing.value
}
const describeFinishEditing = async () => {
  try {
    await formRef.value.validate()
    await moveModelRequest({
      modelId: props.modelId,
      modelDescribe: form.modelDescribe
    })
    describeEditing.value = false
    emit('update:model', form.modelName, form.modelDescribe)
    ElMessage.success('描述修改完成')
  } catch (err) {
    console.error('验证失败', err)
  }
}

const form = reactive({
  modelName: '',
  modelDescribe: ''
})
const rules = reactive({
  modelName: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
  modelDescribe: [{ required: true, message: '请输入模块描述', trigger: 'blur' }]
})
const close = () => {
  emit('update:isShowDrawer')
}
</script>

<style lang="less" scoped>
.label,
.describe {
  margin-bottom: 50px;
  display: flex;
  align-items: center;
}
</style>
